"""
统一读取 config.ini 并转成强类型对象
"""
from __future__ import annotations
import configparser
from dataclasses import dataclass
from pathlib import Path
import sys, os

def resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)


@dataclass(slots=True)
class GlobalCfg:
    device_sn_list: list[str]
    script_path : Path
    apk_dir: Path
    auto_install: bool
    install_only: bool
    skip_if_installed: bool
    rounds: int
    trace: bool
    meminfo: bool
    activity_list: Path
    result_root: Path


def _as_bool(val: str, default: bool = False) -> bool:
    if val is None:
        return default
    return val.strip().lower() in ("1", "yes", "true", "on")


def load_cfg(ini_path: str | Path = "config.ini") -> GlobalCfg:
    """加载配置文件，增加错误处理"""
    cp = configparser.ConfigParser()
    
    # 检查配置文件是否存在
    ini_path = resource_path("config.ini")
    
    
    try:
        cp.read(ini_path, encoding="utf-8")
    except Exception as e:
        raise ValueError(f"读取配置文件失败 {ini_path}: {e}")
    
    # 检查必需的 section
    if "GLOBAL" not in cp:
        raise KeyError("配置文件中缺少 [GLOBAL] section")
    
    g = cp["GLOBAL"]
    
    # 验证必需的配置项
    required_fields = ["apk_dir", "activity_list", "result_root"]
    for field in required_fields:
        if not g.get(field):
            raise ValueError(f"配置文件中缺少必需的字段: {field}")
    
    # 验证路径是否存在
    apk_dir = Path(g.get("apk_dir"))
    if not apk_dir.exists():
        print(f"警告: APK 目录不存在: {apk_dir}")
    
    activity_list = resource_path("activity_list.txt")
    
    try:
        return GlobalCfg(
            device_sn_list=[
                s.strip() for s in g.get("device_sn_list", "").split(",") if s.strip()
            ],
            script_path=Path(g.get("script_path", "")),
            apk_dir=apk_dir,
            auto_install=_as_bool(g.get("auto_install", "true"), True),
            install_only=_as_bool(g.get("install_only", "false")),
            skip_if_installed=_as_bool(g.get("skip_if_installed", "true"), True),
            rounds=g.getint("rounds", fallback=5),
            trace=_as_bool(g.get("trace", "true"), True),
            meminfo=_as_bool(g.get("meminfo", "false")),
            activity_list=activity_list,
            result_root=Path(g.get("result_root", "./results")),
        )
    except Exception as e:
        raise ValueError(f"解析配置失败: {e}")
